package com.my.main.controller.enterprise;


/**
 * 企业管理
 *
 * @author ysy 2021-06-08
 */


import com.my.main.base.controller.BaseController;
import com.my.main.base.entity.Result;
import com.my.main.base.entity.ResultCode;
import com.my.main.common.utils.CurrencyUtil;
import com.my.main.entity.enterprise.Enterprise;
import com.my.main.entity.enterprise.EnterpriseUserRelation;
import com.my.main.service.enterprise.EnterpriseService;
import com.my.main.service.enterprise.EnterpriseUserRelationService;
import com.my.main.service.userAndRight.SysUserService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

//1.解决跨域
@CrossOrigin
//2.声明restContoller
@RestController
//3.设置父路径
@RequestMapping(value="/api/v1/sys/enterprise")
public class EnterpriseController extends BaseController {


    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private EnterpriseService enterpriseService;
    @Autowired
    private EnterpriseUserRelationService enterpriseUserRelationService;


    /**
     * 查询 - 企业管理--企业详情查询
     *
     * @param map
     *
     * @author ysy 2021-06-08
     */
    @ApiOperation(value="企业管理 - 企业详情查询")
    @RequestMapping(value = "/queryData", method = RequestMethod.POST)
    public Result queryData(@RequestBody Map<String, Object> map) {
        Map<String, Object> resMap = new HashMap<>();
        if (StringUtils.isEmpty(map.get("enterpriseId"))) {
            return new Result(ResultCode.FAIL);
        }

        try {
            Enterprise enterprise = enterpriseService.queryStringId(map.get("enterpriseId").toString());
            resMap.put("enterpriseId", enterprise.getEnterpriseId());
            resMap.put("name", enterprise.getName());
            resMap.put("address", enterprise.getAddress());
            resMap.put("contact", enterprise.getContact());
            resMap.put("phone", enterprise.getPhone());
            resMap.put("addTime", enterprise.getAddTime().getTime());
            Map<String, Object> queryMap = new HashedMap<>();
            queryMap.put("enterpriseId", enterprise.getEnterpriseId());
            List<EnterpriseUserRelation> enterpriseUserRelations = enterpriseUserRelationService.queryList(queryMap);
            List<String> userIdList = new ArrayList<>();
            enterpriseUserRelations.stream().forEach(item -> userIdList.add(item.getUserId()));
            resMap.put("userIdList", userIdList);

            return new Result(ResultCode.SUCCESS, resMap);
        } catch (Exception e) {
            logger.error(e);
            return new Result(ResultCode.FAIL, "系统错误，请联系管理员");
        }
    }


    /**
     * 查询 - 企业管理--企业列表查询
     *
     * @param map(page: 页数, limit: 每页条数)
     *
     * @author ysy 2021-06-08
     */
    @ApiOperation(value="企业管理 - 企业列表查询", tags = NOINTERCEPT)
    @RequestMapping(value = "/queryList", method = RequestMethod.POST)
    public Result queryList(@RequestBody Map<String, Object> map) {
        Map<String, Object> resMap = new HashMap<>();
        resMap.put("page", map.get("page"));
        resMap.put("limit", map.get("limit"));

        try {
            map.put("page", CurrencyUtil.PageRowNum(Integer.parseInt(map.get("page").toString()), Integer.parseInt(map.get("limit").toString())));
            Map<String, Object> queryMap = new HashedMap<>();

            List<Map<String, Object>> enterpriseList = new ArrayList<>();
            List<String> empty = new ArrayList<>();
            empty.add("empty");
            if (!userInfo.getIsAdmin()) {
                map.put("enterpriseList", userInfo.getEnterpriseList().size() > 0 ? userInfo.getEnterpriseList() : empty);
            } else {
                // 只有超级管理员才能根据监控管理员姓名筛选
                queryMap.put("realname", map.get("realname"));
                List<String> list = enterpriseUserRelationService.queryByJoinUser(queryMap);
                if (list.size() > 0) {
                    map.put("enterpriseList", list.stream().distinct().collect(Collectors.toList()));
                } else {
                    map.put("enterpriseList", empty);
                }
            }

            List<Enterprise> enterprises = enterpriseService.queryList(map);
            for(Enterprise enterprise: enterprises) {
                Map<String, Object> enterpriseMap = new HashMap<>();
                enterpriseMap.put("enterpriseId", enterprise.getEnterpriseId());
                enterpriseMap.put("name", enterprise.getName());
                enterpriseMap.put("address", enterprise.getAddress());
                enterpriseMap.put("contact", enterprise.getContact());
                enterpriseMap.put("phone", enterprise.getPhone());
                enterpriseMap.put("addTime", enterprise.getAddTime().getTime());
                queryMap.clear();
                queryMap.put("enterpriseId", enterprise.getEnterpriseId());
                List<EnterpriseUserRelation> enterpriseUserRelations = enterpriseUserRelationService.queryList(queryMap);
                List<String> userList = new ArrayList<>();
                enterpriseUserRelations.stream().forEach(item -> userList.add(sysUserService.queryStringId(item.getUserId()).getRealName()));
                enterpriseMap.put("userList", userList);
                enterpriseList.add(enterpriseMap);
            }
            resMap.put("enterpriseList", enterpriseList);
            resMap.put("totalCount", enterpriseService.queryCount(map));
            return new Result(ResultCode.SUCCESS, resMap);
        } catch (Exception e) {
            logger.error(e);
            return new Result(ResultCode.FAIL, "系统错误，请联系管理员");
        }
    }


    /**
     * 保存 - 企业管理--企业保存
     *
     * @param map
     *
     * @author ysy 2021-06-08
     */
    @ApiOperation(value="企业管理 - 企业保存")
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public Result save(@RequestBody Map<String, Object> map) {
        if (StringUtils.isEmpty(map.get("name"))) {
            return new Result(ResultCode.FAIL, "必填项未填写");
        }

        try {
            // 新增企业管理--企业
            if (StringUtils.isEmpty(map.get("enterpriseId"))) {
                enterpriseService.saveData(map, requestUtil.getIp(), userInfo.getUserId());
            } else {
                // 修改
                Enterprise enterprise = enterpriseService.queryStringId(map.get("enterpriseId").toString());
                if (enterprise == null) {
                    return new Result(ResultCode.FAIL, "未找到企业");
                }
                enterpriseService.updateData(map, requestUtil.getIp(), userInfo.getUserId());
            }

            return new Result(ResultCode.SUCCESS);
        } catch (Exception e) {
            logger.error(e);
            return new Result(ResultCode.FAIL,"系统错误，请联系管理员");
        }
    }


    /**
     * 删除 - 企业管理--企业删除
     *
     * @param map
     *
     * @author ysy 2021-06-08
     */
    @ApiOperation(value="企业管理 - 企业删除")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public Result delete(@RequestBody Map<String, Object> map) {
        if (StringUtils.isEmpty(map.get("enterpriseId"))) {
            return new Result(ResultCode.FAIL);
        }

        try {
            enterpriseService.deleteData(map.get("enterpriseId").toString());
            return new Result(ResultCode.SUCCESS);
        } catch (Exception e) {
            logger.error(e);
            return new Result(ResultCode.FAIL,"系统错误，请联系管理员");
        }

    }


}
